package com.lngsyz.eseal.base.util;

import java.util.Random;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

public class SMSUtil {

	public static String sendSMS(String phoneNum) throws Exception {
		boolean isPhone = CommonUtil.isMobile(phoneNum);
		if (!isPhone) {
			throw new Exception("手机号码不正确");
		}
		// 生成验证码
		String verifyCode = randomCode(6);
		JSONObject jo = new JSONObject();
		jo.put("code", verifyCode);
		// 调用接门，发送短信
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5t7e8A3JZKr7NGkau72t",
				"p435rntKZ7iHidWdiw8Pma5hHmHFQB");
		IAcsClient client = new DefaultAcsClient(profile);
		CommonRequest request = new CommonRequest();
		request.setSysMethod(MethodType.POST);
		request.setSysDomain("dysmsapi.aliyuncs.com");
		request.setSysVersion("2017-05-25");
		request.setSysAction("SendSms");
		request.putQueryParameter("RegionId", "cn-hangzhou");
		request.putQueryParameter("PhoneNumbers", phoneNum);
		request.putQueryParameter("SignName", "广烁科技");
		request.putQueryParameter("TemplateCode", "SMS_215730180");
		request.putQueryParameter("TemplateParam", jo.toString());
		CommonResponse response = client.getCommonResponse(request);
		String sendRet = response.getData();
		// {"Message":"OK","RequestId":"48F5B635-42B3-5F29-8A93-0E4D38D9504C","Code":"OK","BizId":"952017903052857101^0"}
		if (StringUtils.isBlank(sendRet)) {
			throw new Exception("短信发送失败，请稍后重试");
		}
		jo = JSONObject.parseObject(sendRet);
		String retCode = jo.getString("Code");
		if (!StringUtils.equals(retCode, "OK")) {
			throw new Exception(jo.getString("Message"));
		}
		return verifyCode;
	}

	private static String randomCode(int length) {
		if (length < 1) {
			length = 6;
		}
		StringBuilder codeBuilder = new StringBuilder();
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			char digitChar = (char) (random.nextInt('9' - '0') + '0'); // 生成0-9之间的随机字符
			codeBuilder.append(digitChar);
		}
		String verificationCode = codeBuilder.toString();
		return verificationCode;
	}
	
	public static void main(String args[]) {
		try {
			sendSMS("15204007695");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
